let Vue;

class Store {
    constructor(options) {
        this.$options = options;
        this.$mutations = options.mutations;
        this.$actions = options.actions;
        // 借助Vue生成响应式数据
        this._vm = new Vue({
            data() {
                return {$$state: options.state}
            },
        })

        // 方法绑定this指向
        this.commit = this.commit.bind(this);
        this.dispatch = this.dispatch.bind(this);
    }

    // this.$store.commit("add", 12)
    commit(type, payload){
       let fn =  this.$mutations[type];
       if(fn){
           fn(this.state, payload)
       }
    }

    dispatch(type, payload){
        let fn =  this.$actions[type];
        if(fn){
          //  return 出去，这样做异步处理
          return  fn(this, payload)
        }
    }
    // 使用get set保护数据源不被直接修改
    get state() {
        return this._vm.$data.$$state;
    }

    set state(value){
        console.error("不可对值直接修改")
    }
}


function install(_Vue) {
    Vue = _Vue;

    Vue.mixin({
        beforeCreate() {
            if (this.$options.store) {
                Vue.prototype.$store = this.$options.store;
            }
        }
    })
}

export default {Store, install}
